package com.zx.servicelearn.activity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.zx.servicelearn.R;
import com.zx.servicelearn.aidl.IMyAidlInterface;
import com.zx.servicelearn.service.MyService4;


/**
 * @作者 zhoux
 * @创建时间 2017/12/21
 * @描述 aidl学习
 * @修改时间 2017/12/21
 * @修改描述
 * @修改者 zhoux
 **/
public class ServiceLearn4Activity extends AppCompatActivity {
    String TAG = "ServiceLearn4Activity";
    TextView testShow_tv;

    /**
     * 主线程handler，用于处理UI
     */
    Handler mainHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 1:
                    String msgText = (String) msg.obj;
                    if (msgText != null)
                        testShow_tv.setText("" + msgText);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service_learn4);
        testShow_tv = findViewById(R.id.testShow_tv);
    }

    private IMyAidlInterface myService;
    ServiceConnection myServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myService = IMyAidlInterface.Stub.asInterface(service);
            try {
                int c = myService.plus(1, 2);
                int d = myService.muti(1, 2);
                Log.e(TAG, "IMyAidlInterface exc" + c);//
                Log.e(TAG, "IMyAidlInter" +
                        "face exc" + d);//
                mainHandler.sendMessage(mainHandler.obtainMessage(1, "c:" + c + "d：" + d));
            } catch (RemoteException e) {
                e.printStackTrace();
            }
//            unbindService(myServiceConnection);

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    public void bindServiceTest(View view) {
        Intent intent = new Intent(this, MyService4.class);
        bindService(intent, myServiceConnection, BIND_AUTO_CREATE);//
    }

    public void unBindServiceTest(View view) {//
        try {
            unbindService(myServiceConnection);
        } catch (Exception e) {

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            unbindService(myServiceConnection);//
        } catch (Exception e) {

        }
    }
}
